import react from "@vitejs/plugin-react";
import { resolve } from "node:path";
import type { UserConfig } from "vite";
import { defineConfig, loadEnv } from "vite";
import { autoComplete, Plugin as ImportToCDN } from "vite-plugin-cdn-import";
import eslintPlugin from "vite-plugin-eslint";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";

export default defineConfig(({ mode }): UserConfig => {
	const env = loadEnv(mode, "./env");
	return {
		envDir: "./env",
		plugins: [
			react(),
			eslintPlugin({
				include: ["src/**/*.ts", "src/**/*.tsx", "src/*.ts"],
				exclude: ["./node_modules/**"],
				failOnError: true,
				cache: false
			}),
			createSvgIconsPlugin({
				iconDirs: [resolve("./src/assets/svg")],
				symbolId: "[name]"
			}),
			ImportToCDN({
				prodUrl: "https://cdn.jsdelivr.net/npm/{name}@{version}/{path}",
				modules: [autoComplete("react"), autoComplete("react-dom"), autoComplete("ahooks"), autoComplete("axios")]
			})
		],
		resolve: {
			alias: [{ find: "@", replacement: resolve("./src") }],
			extensions: [".js", ".ts", ".tsx", ".scss", ".css"]
		},
		css: {
			preprocessorOptions: {
				scss: {
					additionalData: `@import "@/styles/variables.scss"; @import "@/styles/mixins.scss";`
				}
			}
		},
		build: {
			target: "modules",
			outDir: "dist",
			assetsDir: "static",
			cssCodeSplit: true,
			sourcemap: env.VITE_PROJECT_ENV !== "production",
			minify: "terser",
			terserOptions: {
				compress: {
					drop_console: env.VITE_PROJECT_ENV === "production",
					drop_debugger: env.VITE_PROJECT_ENV === "production"
				}
			},
			rollupOptions: {
				output: {
					chunkFileNames: "assets/js/[name]-[hash].js",
					entryFileNames: "assets/js/[name]-[hash].js",
					assetFileNames: "assets/[ext]/[name]-[hash].[ext]"
				}
			}
		},
		server: {
			port: 8080,
			open: true,
			host: true,
			cors: true,
			// headers: {
			// 	"Access-Control-Allow-Origin": "*"
			// },
			proxy: {
				"/ruta_api": {
					target: env.VITE_BASE_URL,
					changeOrigin: true,
					// rewrite: path => path.replace(/^\/api/, "")
					rewrite: path => path
				}
			}
		}
	};
});
